<template>
  <!--下方查看详情表格面板-->
  <div v-if="showTable" class="new-queryResultDiv" style="height:500px">
    <div class="new-queryTableBtn">
      <el-button @click="closeTableDiv" type="primary">关闭</el-button>
      <el-button @click="deleteSelectData" type="primary" >删除</el-button>
    </div>
    <div class="new-queryTableDiv">
      <el-form ref="formTable" :model="tableDataForm" style="height:100%;">
        <!--数据表格-->
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane v-for="(it,index) in dataList" :key="it.typeName" :label="it.typeName" :name="it.typeName" @tab-change="tabChange">
              <el-table v-loading="loading" ref="multipleTable" @row-click="rowClick" :data="tableDataForm.tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" tooltip-effect="dark"
                height="100%" @selection-change="handleSelectionChange" :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }" stripe>
                <el-table-column :selectable="checkboxSelect" type="selection" width="50"></el-table-column>
                <el-table-column label="序号" width="55" type="index" align="center">
                  <template #default="scope">
                    <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <template v-if="it.typeName == '重大工程历史震害'">
                  <el-table-column v-for="(item, index) in tableColumns1" :key="'type1.' + index + '.'+item.filedProp" :width="160"
                              :prop="item.filedProp" :label="item.filedName">
                    <template #default="scope">
                      <span v-if="!scope.row.isEdit">
                        {{ scope.row.dictItemNameObj[item.filedProp] }}
                      </span>
                      <el-form-item v-else :prop="'tableData.' + scope.$index + '.' + item.filedProp" :rules="tableDataForm.rules1[item.filedProp]">
                        <el-select v-if="item.filedType=='select'" v-model="scope.row[item.filedProp]" @change="(value) => onChangeSelect(value,item.filedProp,scope.row)"
                                  :disabled="item.readonly=='readonly'" placeholder="请选择" clearable>
                          <el-option v-for="item in getDictArray(scope.row,item.filedProp,item.filedName,activeName)" :key="item.code" :label="item.name"
                                    :value="item.code">
                          </el-option>
                        </el-select>
                        <el-date-picker v-else-if="item.filedType=='datetime'" v-model="scope.row[item.filedProp]"
                                        type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择">
                        </el-date-picker>
                        <el-time-picker
                          v-else-if="item.filedType=='time'"
                          v-model="scope.row[item.filedProp]"
                          value-format="HH:mm:ss"
                          placeholder="请选择"
                        />
                        <el-input v-else-if="item.readonly=='readonly'" v-model.trim="scope.row.dictItemNameObj[item.filedProp]" :disabled="item.readonly=='readonly'"></el-input>
                        <el-input v-else v-model.trim="scope.row[item.filedProp]"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </template>
                <template v-if="it.typeName == '水库大坝'">
                  <el-table-column v-for="(item, index) in tableColumns2" :key="'type2.' + index + '.'+item.filedProp" :width="160"
                              :prop="item.filedProp" :label="item.filedName">
                    <template #default="scope">
                      <span v-if="!scope.row.isEdit">
                        {{ scope.row.dictItemNameObj[item.filedProp] }}
                      </span>
                      <el-form-item v-else :prop="'tableData.' + scope.$index + '.' + item.filedProp" :rules="tableDataForm.rules2[item.filedProp]">
                        <el-select v-if="item.filedType=='select'" v-model="scope.row[item.filedProp]" @change="(value) => onChangeSelect(value,item.filedProp,scope.row)"
                                  :disabled="item.readonly=='readonly'" placeholder="请选择" clearable>
                          <el-option v-for="item in getDictArray(scope.row,item.filedProp,item.filedName,activeName)" :key="item.code" :label="item.name"
                                    :value="item.code">
                          </el-option>
                        </el-select>
                        <el-input v-else-if="item.readonly=='readonly'" v-model.trim="scope.row.dictItemNameObj[item.filedProp]" :disabled="item.readonly=='readonly'"></el-input>
                        <el-input v-else v-model.trim="scope.row[item.filedProp]"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </template>
                <el-table-column label="操作" fixed="right" width="120">
                  <template #default="scope">
                    <el-button type="text" size="small" @click="handleModify(scope.$index, scope.row,it.typeName)"
                      :disabled="scope.row.createUser != currentUserId">
                      {{ scope.row.isEdit ? '应用' : '修改' }}
                    </el-button>
                    <el-button type="text" size="small" @click="handleDelete(scope.$index, scope.row,it.typeName)"
                      :disabled="scope.row.createUser != currentUserId">删除</el-button>
                  </template>
                </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <!--分页显示-->
    <div class="new-queryTableDiv-page">
      <el-pagination v-if="tableDataForm.tableData.length > 0" v-model:current-page="currentPage"
        v-model:page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="tableDataForm.tableData.length"
        @current-change="handleCurrentChange" @size-change="handleSizeChange" />
    </div>
  </div>
</template>
<script setup>
import { repeatData,getVersionCode,updateData,deleteData,deleteByTypeAndVersionId,getValidDictItemsByDictCode,getByRange, } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
import { queryByPage, findById, } from "@/api/map/disasterDataManagement/majorEngineerFacInfo.js";
import { reactive, toRefs } from "vue";
import { getInfo } from '@/api/login';
import { getUserId } from "@/utils/auth";
import { ElMessage, ElMessageBox } from 'element-plus';
import { getProvince, getChildArea } from "@/api/system/division";

//验证是否正整数（非必填）
const isIntegerNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入正整数'));
  } else if (Number(value) < 0) {
    callback(new Error('请输入正整数'));
  } else if (Number(value).toString().indexOf(".") != -1) {
    callback(new Error('请输入正整数'));
  } else {
    callback();
  }
}

//验证是否正数（非必填）
const isNumberNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入正数'));
  } else if (Number(value) < 0) {
    callback(new Error('请输入正数'));
  } else {
    callback();
  }
}

//验证是否yyyy年份（非必填）
const isYearNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().length != 4) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().indexOf(".") != -1) {
    callback(new Error('请输入yyyy格式如2022'));
  } else {
    callback();
  }
}

// 验证经度（非必填）
const validateLon = (rule, value, callback) => {
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g; // 整数或小数
  if (!value) {
    callback()
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确数值'))
  } else if (value > 180) {
    callback(new Error('经度必须小于180'))
  } else if (value < 0) {
    callback(new Error('经度必须大于0'))
  } else if (value.indexOf(".") != -1 && value.split(".")[1].length > 15) {
    callback(new Error('最多保留15位小数'));
  } else {
    callback();
  }
}

// 验证纬度（非必填）
const validateLat = (rule, value, callback) => {
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g; // 整数或小数
  if (!value) {
    callback()
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确数值'))
  } else if (value > 90) {
    callback(new Error('纬度必须小于90'))
  } else if (value < 0) {
    callback(new Error('纬度必须大于0'))
  } else if (value.indexOf(".") != -1 && value.split(".")[1].length > 15) {
    callback(new Error('最多保留15位小数'));
  } else {
    callback();
  }
}
const props = defineProps({
  resultShowTable: {
    type: Boolean,
    default: false
  },
  mapParams: {
    type: Object,
    default: {}
  },
  selectType: {
    type: String,
    default: ''
  },
});
const data = reactive({
  params: {
    province: "",
    city: "",
    county: "",
    type: "",//数据类型
    page: 1,
    rows: 10,
  },
  tableDataForm: {
    tableData: [],//表格数据
    //通用字段
    rules0: {
      province: [{required: false, message: '请输入省', trigger: 'blur'},],
      city: [{required: false, message: '请输入市', trigger: 'blur'},],
      county: [{required: false, message: '请输入区县', trigger: 'blur'},],
      extends1: [{required: false, message: '请输入extends1', trigger: 'blur'},],
      extends2: [{required: false, message: '请输入extends2', trigger: 'blur'},],
      extends3: [{required: false, message: '请输入extends3', trigger: 'blur'},],
      extends4: [{required: false, message: '请输入extends4', trigger: 'blur'},],
      extends5: [{required: false, message: '请输入extends5', trigger: 'blur'},],
      extends6: [{required: false, message: '请输入extends6', trigger: 'blur'},],
      extends7: [{required: false, message: '请输入extends7', trigger: 'blur'},],
      extends8: [{required: false, message: '请输入extends8', trigger: 'blur'},],
      extends9: [{required: false, message: '请输入extends9', trigger: 'blur'},],
      extends10: [{required: false, message: '请输入extends10', trigger: 'blur'},],
    },
    //重大工程历史震害
    rules1: {
      seismName: [{required: true, message: '请输入地震名称', trigger: 'blur'},],
      seismData: [{required: true, message: '请输入发生日期', trigger: 'blur'},],
      seismTime: [{required: true, message: '请输入发生时间', trigger: 'blur'},],
      magnitude: [{required: true, message: '请输入震级', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      projectType: [{required: true, message: '请输入重大工程类型', trigger: 'change'},],
      fortification: [{required: true, message: '请输入设防情况', trigger: 'change'},],
      year: [{required: true, message: '请输入年代', trigger: 'change'}],
      // defenseSituation: [{required: true, message: '请输入地震动参数（烈度）', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      // destructiveState: [{required: true, message: '请输入破坏状态', trigger: 'blur'},],
    },
    //水库大坝
    rules2: {
      crName: [{required: true, message: '请输入水坝名称', trigger: 'blur'},],
      location: [{required: true, message: '请输入水坝地点', trigger: 'blur'},],
      longitude: [{required: true, message: '请输入经度', trigger: 'blur'},{trigger: 'blur',validator: validateLon}],
      latitude: [{required: true, message: '请输入纬度', trigger: 'blur'},{trigger: 'blur',validator: validateLat}],
      capacity: [{required: true, message: '请输入库容（立方米）', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      year: [{required: true, message: '请输入建造年代', trigger: 'blur'},{trigger: 'blur',validator: isYearNotMust}],
      damLength: [{required: true, message: '请输入坝长', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      damHeight: [{required: true, message: '请输入坝高', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      topWidth: [{required: true, message: '请输入顶宽', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      structureType: [{required: true, message: '请输入结构类型', trigger: 'change'},],
      type: [{required: true, message: '请输入水坝类型', trigger: 'change'},],
      intensity: [{required: true, message: '请输入设防烈度', trigger: 'change'},],
      site: [{required: true, message: '请输入位置', trigger: 'change'},],
      space: [{required: true, message: '请输入场地', trigger: 'change'},],
      filling: [{required: true, message: '请输入填料', trigger: 'change'},],
      damFoundation: [{required: true, message: '请输入坝基', trigger: 'change'},],
      maintenanceStatus: [{required: true, message: '请输入维护现状', trigger: 'change'},],
    },
  },
});
const {
  params, tableDataForm,
} = toRefs(data);
const { proxy } = getCurrentInstance();
const showTable = ref(false)
const activeName = ref('')
//数据类型
const dataTypeInfoArray = ref([
  { code: "16", name: "重大工程历史震害" },
  { code: "17", name: "水库大坝" },
]);
const dataTypeArray = ref(["重大工程历史震害", "水库大坝"]);
//通用字段
const tableColumns0 = ref([
  // { filedProp:"province", filedName:"省", filedType:"select" },
  // { filedProp:"city", filedName:"市", filedType:"select" },
  // { filedProp:"county", filedName:"区县", filedType:"select" },
  // { filedProp:"extends1", filedName:"extends1", filedType:"input" },
  // { filedProp:"extends2", filedName:"extends2", filedType:"input" },
  // { filedProp:"extends3", filedName:"extends3", filedType:"input" },
  // { filedProp:"extends4", filedName:"extends4", filedType:"input" },
  // { filedProp:"extends5", filedName:"extends5", filedType:"input" },
  // { filedProp:"extends6", filedName:"extends6", filedType:"input" },
  // { filedProp:"extends7", filedName:"extends7", filedType:"input" },
  // { filedProp:"extends8", filedName:"extends8", filedType:"input" },
  // { filedProp:"extends9", filedName:"extends9", filedType:"input" },
  // { filedProp:"extends10", filedName:"extends10", filedType:"input" },
  { filedProp:"createUser", filedName:"创建人", filedType:"input", readonly:"readonly" },
  { filedProp:"createTime", filedName:"创建时间", filedType:"input", readonly:"readonly" },
  { filedProp:"updateUser", filedName:"修改人", filedType:"input", readonly:"readonly" },
  { filedProp:"updateTime", filedName:"修改时间", filedType:"input", readonly:"readonly" },
]);

//重大工程历史震害
const tableColumns1 = ref([
  // { filedProp:"id", filedName:"序号", filedType:"input" },
  { filedProp:"seismName", filedName:"地震名称", filedType:"input" },
  { filedProp:"seismDate", filedName:"发生日期", filedType:"date" },
  { filedProp:"seismTime", filedName:"发生时间", filedType:"time" },
  { filedProp:"magnitude", filedName:"震级", filedType:"input" },
  { filedProp:"projectType", filedName:"重大工程类型", filedType:"select" },
  { filedProp:"fortification", filedName:"设防情况", filedType:"select" },
  { filedProp:"year", filedName:"年代", filedType:"select" },
  { filedProp:"destructive6State", filedName:"6度破坏状态", filedType:"select" },
  { filedProp:"destructive7State", filedName:"7度破坏状态", filedType:"select" },
  { filedProp:"destructive8State", filedName:"8度破坏状态", filedType:"select" },
  { filedProp:"destructive9State", filedName:"9度破坏状态", filedType:"select" },
  { filedProp:"destructive10State", filedName:"10度破坏状态", filedType:"select" },
  { filedProp:"destructive11State", filedName:"11度破坏状态", filedType:"select" },
  { filedProp:"destructive12State", filedName:"12度破坏状态", filedType:"select" },
  ...tableColumns0.value
]);

//水库大坝
const tableColumns2 = ref([
  { filedProp:"crName", filedName:"水坝名称", filedType:"input" },
  { filedProp:"location", filedName:"水坝地点", filedType:"input" },
  { filedProp:"longitude", filedName:"经度", filedType:"number", readonly:"readonly" },
  { filedProp:"latitude", filedName:"纬度", filedType:"number", readonly:"readonly" },
  { filedProp:"capacity", filedName:"库容（立方米）", filedType:"number" },
  { filedProp:"year", filedName:"建造年代", filedType:"input" },
  { filedProp:"damLength", filedName:"坝长", filedType:"number" },
  { filedProp:"damHeight", filedName:"坝高", filedType:"number" },
  { filedProp:"topWidth", filedName:"顶宽", filedType:"number" },
  { filedProp:"structureType", filedName:"结构类型", filedType:"select" },
  { filedProp:"type", filedName:"水坝类型", filedType:"select" },
  { filedProp:"intensity", filedName:"设防烈度", filedType:"select" },
  { filedProp:"site", filedName:"位置", filedType:"select" },
  { filedProp:"space", filedName:"场地", filedType:"select" },
  { filedProp:"filling", filedName:"填料", filedType:"select" },
  { filedProp:"damFoundation", filedName:"坝基", filedType:"select" },
  { filedProp:"maintenanceStatus", filedName:"维护现状", filedType:"select" },
  ...tableColumns0.value
]);
//全部表格字段信息数组
const allTableColumns = ref([
  tableColumns1.value, tableColumns2.value
]);
const emits = defineEmits(['closeTableDiv','rowClickData']);
//关闭
const closeTableDiv = () => {
  emits("closeTableDiv");
}

const dataList = ref([])
watch(() => props.resultShowTable, val => {
  if(val == false){
    showTable.value = false
  }else{
    if(JSON.stringify(props.mapParams) != '{}') {
      proxy.$modal.loading("正在查询...");
      getMapSelectData()
    }
  }
}, { deep: true, immediate: true });
watch(() => props.mapParams, () => {
  // if(JSON.stringify(props.mapParams) != '{}') {
  //   if(props.resultShowTable == true) {
  //     proxy.$modal.loading("正在查询...");
  //     getMapSelectData()
  //   }
  // }else{
  //   showTable.value = false
  // }
}, { deep: true, immediate: true });
function getMapSelectData() {
  dataList.value = []
  getByRange(props.mapParams).then(res => {
    let list = res.data
    for(let key in list) {
      if(list[key].length !=0) {
        let name = dataTypeInfoArray.value.find(item => item.code == key).name
        dataList.value.push({code: key,typeName: name,value:list[key]})
      }
    }
    if(dataList.value.length != 0) {
      for(let q = 0;q < dataList.value.length;q++){
        let listData = dataList.value[q].value
        for (let i = 0; i < listData.length; i++) {
          let typeIndex = dataTypeArray.value.indexOf(dataList.value[q].typeName);
          let allTableColumnsArray = allTableColumns.value;
          let tableColumnsArray = allTableColumnsArray[typeIndex];
          listData[i].isEdit = false;//是否编辑状态
          //创建字典值对象
          listData[i].dictItemNameObj = Object.create(null);
          if (dataList.value[q].typeName == "电力-架空线路") {
            // { superColumnName:"评价单元信息(精确到县区）", filedArray:[
            for (let j = 0; j < tableColumnsArray.length; j++) {
              let superColumnName = tableColumnsArray[j].superColumnName;
              let filedArray = tableColumnsArray[j].filedArray;
              for (let k = 0; k < filedArray.length; k++) {
                let filedProp = filedArray[k].filedProp;
                let filedName = filedArray[k].filedName;
                /*let filedValue = result[i][filedProp];
                if(filedValue && typeof filedValue==="string"){
                  let trimValue = filedValue.trim();//去除两侧空格
                  result[i][filedProp] = trimValue;
                }*/
                let dictItemName = dictChange(i, listData[i], filedProp, filedName, dataList.value[q].typeName);
                //获取字典值
                listData[i].dictItemNameObj[filedProp] = dictItemName;
              }
            }
          } else {
            for (let j = 0; j < tableColumnsArray.length; j++) {
              let filedProp = tableColumnsArray[j].filedProp;
              let filedName = tableColumnsArray[j].filedName;
              /*let filedValue = result[i][filedProp];
              if(filedValue && typeof filedValue==="string"){
                let trimValue = filedValue.trim();//去除两侧空格
                result[i][filedProp] = trimValue;
              }*/
              let dictItemName = dictChange(i, listData[i], filedProp, filedName, dataList.value[q].typeName);
              //获取字典值
              listData[i].dictItemNameObj[filedProp] = dictItemName;
            }
          }
        }
      }
      activeName.value = dataList.value[0].typeName
      tableDataForm.value.tableData = dataList.value[0].value
    }
    showTable.value = true
    proxy.$modal.closeLoading();
  }).catch(err => {
    proxy.$modal.closeLoading();
  })
}
function tabChange(tabName) {
  let data = dataList.value.find(item => item.typeName == tabName)
  tableDataForm.value.tableData = data.value
}
// 转换时间
function getFormatTime(time) {
  if (time && time !== "") {
    let d = new Date(time);
    let year = d.getFullYear();
    let month = d.getMonth() + 1;
    if (month < 10) month = "0" + month;
    let date = d.getDate();
    if (date < 10) date = "0" + date;
    let hours = d.getHours();
    if (hours < 10) hours = "0" + hours;
    let minutes = d.getMinutes();
    if (minutes < 10) minutes = "0" + minutes;
    let seconds = d.getSeconds();
    if (seconds < 10) seconds = "0" + seconds;
    let newTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
    return newTime;
  } else {
    return "";
  }
}
//数据解析
const dictChange = (index, data, col, colName, dataType) => {
  if (col == "createUser" || col == "updateUser") {
    // 获取用户名
    return getUserInfo(index, data, col);
  } else if (col == "createTime" || col == "updateTime") {
    // 格式化时间
    return getFormatTime(data[col]);
  } else {
    let dictArr = getDictArray(data, col, colName, dataType);
    if (data[col] != null && dictArr != null && dictArr.length > 0) {
      let code = data[col];
      /*if(code && typeof code==="string"){
        let trimValue = code.trim();//去除两侧空格
        code = trimValue;
      }*/
      for (let item of dictArr) {
        if (item.code == code) {
          //字典值
          return item.name;
        }
      }
    }
  }
  return data[col];
}
//获取字典数组
function getDictArray(data, col, colName, dataType) {
  let array = null;
  let dictCode = null;
  if(colName.indexOf("液化程度")!=-1 || colName.indexOf("震陷程度")!=-1){
    dictCode = "smxyhcd";
  }else if(colName=="场地类别" || colName=="场地土分类" || colName=="场地类型"){
    dictCode = "smxcdlb";
  }else if(colName=="设防烈度" || colName=="抗震设防烈度" || colName=="评价单元设防烈度" || colName=="设防标准" || colName=="设防情况"){
    dictCode = "smxsfqk";
  }
  if(dataType=="重大工程历史震害"){
    if(colName=="6度破坏状态" || colName=="7度破坏状态" || colName=="8度破坏状态" || colName=="9度破坏状态" || colName=="10度破坏状态" || colName=="11度破坏状态" || colName=="12度破坏状态"){
      array = [
        {code:"基本完好",name:"基本完好"},
        {code:"轻微破坏",name:"轻微破坏"},
        {code:"中等破坏",name:"中等破坏"},
        {code:"严重破坏",name:"严重破坏"},
        {code:"倒塌",name:"倒塌"},
      ];
      dictCode = null;
    }else if(colName == '年代') {
      array = [
        {code:"1978年以前",name:"1978年以前"},
        {code:"1978-1989年",name:"1978-1989年"},
        {code:"1989-2001年",name:"1989-2001年"},
        {code:"2001年以后",name:"2001年以后"},
      ];
      dictCode = null;
    }else if(colName == '重大工程类型') {
      array = [
        {code:"输油管线",name:"输油管线"},
        {code:"输气管线",name:"输气管线"},
        {code:"核电站",name:"核电站"},
        {code:"水库大坝",name:"水库大坝"},
      ];
      dictCode = null;
    }
  }else if(dataType=="水库大坝"){
    if(colName=="结构类型"){
      dictCode = "skdbjglx";
    }else if(colName=="水坝类型"){
      dictCode = "skdbsblx";
    }else if(colName=="场地"){
      dictCode = "skdbcd";
    }else if(colName=="填料"){
      dictCode = "skdbtl";
    }else if(colName=="坝基"){
      dictCode = "skdbbj";
    }else if(colName=="维护现状"){
      dictCode = "skdbwhxz";
    }else if(colName=="位置"){
      array = [
        {code:"上游",name:"上游"},
        {code:"中游",name:"中游"},
        {code:"下游",name:"下游"},
      ];
    }else if(colName=="设防烈度"){
      array = [
        {code:"无设防",name:"无设防"},
        {code:"6度设防",name:"6度设防"},
        {code:"7度设防",name:"7度设防"},
        {code:"9度设防",name:"9度设防"},
        {code:"10度设防",name:"10度设防"},
        {code:"加固",name:"加固"},
        {code:"不详",name:"不详"},
      ];
      dictCode = null;
    }
  }
  if (dictCode) {
    //字典表
    let allArray = allDictArray.value;
    for (let i = 0; i < allArray.length; i++) {
      if (allArray[i].dictCode == dictCode) {
        array = [];
        let dictItems = allArray[i].dictItems;
        for (let i = 0; i < dictItems.length; i++) {
          let code = dictItems[i].dictItemCode;
          if (dataType == "通信-电视塔" && colName == "设防标准") {
            code = Number(code);
          }
          let obj = {
            code: code,
            name: dictItems[i].dictItemName,
          }
          array.push(obj);
        }
        break;
      }
    }
  } else {
    if (data.isEdit) {//编辑状态
      //省市县下拉选择
      if (colName == "省") {
        array = [];
        let provinceArray = provinceData.value;
        for (let i = 0; i < provinceArray.length; i++) {
          let obj = {
            code: provinceArray[i].name,
            name: provinceArray[i].name,
          }
          array.push(obj);
        }
      } else if (colName == "市") {
        array = [];
        let province = data["province"];
        //根据省获取市列表
        let cityArray = chooseProvince(province);
        for (let i = 0; i < cityArray.length; i++) {
          let obj = {
            code: cityArray[i].name,
            name: cityArray[i].name,
          }
          array.push(obj);
        }
      } else if (colName == "区县") {
        array = [];
        let province = data["province"];
        let city = data["city"];
        //根据省获取市列表
        let cityArray = chooseProvince(province);
        for (let i = 0; i < cityArray.length; i++) {
          if (cityArray[i].name == city) {
            //根据市获取区县列表
            let countyArray = chooseCity(cityArray[i].id);
            for (let i = 0; i < countyArray.length; i++) {
              let obj = {
                code: countyArray[i].name,
                name: countyArray[i].name,
              }
              array.push(obj);
            }
            break;
          }
        }
      }
    }
  }
  return array;
}
//字典表信息数组
const dictInfoArray = ref([
  {dictCode:"smxyhcd",dictName:"生命线-液化程度和震陷程度"},
  {dictCode:"smxsfqk",dictName:"生命线-设防情况"},
  {dictCode:"smxsfld",dictName:"生命线-设防烈度"},
  {dictCode:"smxcdlb",dictName:"生命线-场地类别"},
  {dictCode:"skdbjglx",dictName:"生命线-水库大坝-结构类型"},
  {dictCode:"skdbsblx",dictName:"生命线-水库大坝-水坝类型"},
  {dictCode:"skdbcd",dictName:"生命线-水库大坝-场地"},
  {dictCode:"skdbtl",dictName:"生命线-水库大坝-填料"},
  {dictCode:"skdbbj",dictName:"生命线-水库大坝-坝基"},
  {dictCode:"skdbwhxz",dictName:"生命线-水库大坝-维护现状"},
]);
//全部字典表数组
const allDictArray = ref([]);
//获取全部字典表
function getAllDictArray() {
  allDictArray.value = [];//清空
  let array = dictInfoArray.value;
  for (let i = 0; i < array.length; i++) {
    let dictCode = array[i].dictCode;
    //字典表查询
    getValidDictItems(dictCode);
  }
}

//字典表查询
function getValidDictItems(dictCode) {
  //查询
  getValidDictItemsByDictCode(dictCode).then((response) => {
    nextTick(() => {
      let dictItems = response.data;
      let obj = {
        dictCode: dictCode,
        dictItems: dictItems
      };
      allDictArray.value.push(obj);
    });
  }).catch(err => {
    console.log(err);
  });
}
const currentUserId = ref(null);//当前登录人ID
const provinceData = ref([]); //全部省
const allCityData = ref(new Map()); //全部市
const allCountyData = ref(new Map()); //全部区县
/** 获取省列表 */
function getProvinceData() {
  provinceData.value = [];
  allCityData.value = new Map();
  allCountyData.value = new Map();
  //全部省
  getProvince().then((response) => {
    let provinceArray = response.data;
    provinceData.value = provinceArray;
    for (let i = 0; i < provinceArray.length; i++) {
      //获取市列表
      getCityData(provinceArray[i].id);
    }
  });
}

//获取市列表
function getCityData(provinceId) {
  getChildArea(provinceId).then(response => {
    let cityArray = response.data;
    allCityData.value.set(provinceId, cityArray);
    for (let i = 0; i < cityArray.length; i++) {
      //获取区县列表
      getCountyData(cityArray[i].id);
    }
  });
}

//获取区县列表
function getCountyData(cityId) {
  getChildArea(cityId).then(response => {
    let countyData = response.data;
    allCountyData.value.set(cityId, countyData);
  });
}

//根据省名获取省ID
function getProvinceId(name) {
  let provinceId = null;
  let provinceArray = provinceData.value;
  for (let i = 0; i < provinceArray.length; i++) {
    if (provinceArray[i].name == name) {
      provinceId = provinceArray[i].id;
      break;
    }
  }
  return provinceId;
}

//根据省获取市列表
const chooseProvince = (name) => {
  let cityData = [];
  let provinceId = getProvinceId(name);//根据省名获取省ID
  if (provinceId) {
    cityData = allCityData.value.get(provinceId);
  }
  return cityData;
}
//根据市获取区县列表
const chooseCity = (cityId) => {
  let areaData = [];
  if (cityId) {
    areaData = allCountyData.value.get(cityId);
  }
  return areaData;
}
//当前登录人ID
function getCurrentUserId() {
  let userId = getUserId();
  currentUserId.value = userId;
}
const userInfoMap = ref(new Map());//用户信息Map
// 获取用户名
function getUserInfo(index, data, col) {
  let userName = "";
  let userId = data[col];
  if (userId) {
    userName = userInfoMap.value.get(userId);
    if (userName == undefined) {
      userName = "";
      //用户信息Map
      userInfoMap.value.set(userId, userName);
      //获取用户信息
      getInfo(userId).then(response => {
        userName = response.user.userName;
        //用户信息Map
        userInfoMap.value.set(userId, userName);
        //遍历更新用户数据
        let tableData = tableDataForm.value.tableData;
        for (let i = 0; i < tableData.length; i++) {
          if (tableData[i].createUser == userId) {
            //设置用户名
            tableDataForm.value.tableData[i].dictItemNameObj["createUser"] = userName;
          }
          if (tableData[i].updateUser == userId) {
            //设置用户名
            tableDataForm.value.tableData[i].dictItemNameObj["updateUser"] = userName;
          }
        }
      });
    }
  }

  return userName;
}
const multipleSelection = ref([])
//查询结果多选事件
function handleSelectionChange(val) {
  multipleSelection.value = val;
}
//分页显示表格数据
const currentPage = ref(1);//当前页码
const pageSize = ref(10);//每页显示数据数量
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  currentPage.value = 1;
  pageSize.value = val;
};
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
};
//删除选择的数据
function deleteSelectData() {
  let ids = "";
  let selectRows = multipleSelection.value;
  if (selectRows != null && selectRows.length > 0) {
    if (selectRows.length > 10) {
      proxy.$modal.msgWarning("最多勾选10条数据进行删除!");
      return;
    }
    for (let i = 0; i < selectRows.length; i++) {
      if (ids != "") {
        ids += ",";
      }
      let uuid = getRowUuid(selectRows[i],activeName.value);//根据数据类型获取主键id
      //主键
      if (uuid) {
        ids += uuid;
      }
    }
    //删除事件
    deleteEvent(ids, selectRows,activeName.value);
  } else {
    proxy.$modal.msgWarning("请勾选1条数据进行删除!");
  }
}
//删除事件
function deleteEvent(ids, rows,selectType) {
  console.log(rows,'lallal');
  if (ids && ids !== "") {
    // let type = (dataTypeArray.value.indexOf(props.selectType) + 1).toString();//数据类型
    let type = getSelectTypeNumStr(selectType);
    proxy.$modal
        .confirm("请确认是否要删除？",)
        .then(function () {
          let formMap = new Map();
          formMap.set("ids", ids);
          //map转obj
          let obj = Object.create(null);
          for (let [k, v] of formMap) {
            obj[k] = v;
          }
          let data = {
            ...obj,
            type: type
          }
          //删除数据
          return deleteData(data);
        })
        .then(() => {
          //查询数据
          getMapSelectData()
          proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
  }
}
//获取数据类型序号
function getSelectTypeNumStr(type) {
  let code = null;
  let dataTypeArr = dataTypeInfoArray.value;
  for (let i = 0; i < dataTypeArr.length; i++) {
    if (dataTypeArr[i].name == type) {
      code = dataTypeArr[i].code;
      break;
    }
  }
  return code;
}
const rowClick = (row) => {
  emits('rowClickData',row)
}
const checkboxSelect = (row) => {
  if (row.createUser == currentUserId.value) {
    return true
  } else {
    return false
  }
}
//修改
const handleModify = (index, row,selectType) => {
  if (row.isEdit) {//保存修改
    let type = getSelectTypeNumStr(selectType);
    let formMap = new Map();
    formMap.set(type, row);
    //map转obj
    let obj = Object.create(null);
    for (let [k, v] of formMap) {
      obj[k] = v;
    }
    //校验
    proxy.$refs['formTable'].validate((valid, fields) => {
      if (valid) {
        //更新数据
        updateData(obj).then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '修改成功!'
            });
            row.isEdit = false;
            //查询数据
            getMapSelectData()
          }
        }).catch(err => {
          console.log(err);
        });
      } else {
        proxy.$modal.msgWarning("校验失败!");
        proxy.$refs['formTable'].scrollToField(Object.keys(fields)[0]);
      }
    });
  } else {//开启修改
    row.isEdit = true;
  }
}
//删除
const handleDelete = (index, row,selectType) => {
  let uuid = getRowUuid(row,selectType);//根据数据类型获取主键id
  let rows = [row];
  //删除事件
  deleteEvent(uuid, rows,selectType);
}
//根据数据类型获取主键id
function getRowUuid(row,type) {
  let selectType = type;
  let uuid = null;
  if (row) {
    if (selectType == '重大工程历史震害') {
      uuid = row.id;
    } else if (selectType == '水库大坝') {
      uuid = row.id;
    }
  }

  return uuid;
}
//获取省列表
getProvinceData();
//当前登录人ID
getCurrentUserId();
//获取全部字典表
getAllDictArray();
</script>
<style lang="scss" scoped>
.min-Table {
  height: 500px;
}
//下方查看详情面板
.new-queryResultDiv {
  position: absolute;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background: #fff;
  z-index: 10;
  border: 1px solid #e4e7ed;
}

.new-queryTableBtn {
  position: absolute;
  left: 0px;
  right: 0px;
  top: 0px;
  height: 50px;
  padding: 10px;
}

.new-queryTableSpan {
  position: relative;
  top: -32px;
  width: 100%;
  text-align: center;
  font-weight: bold;
  font-size: 18px;
  color: #107ce5;
  display: inline-block;
  line-height: 32px;
  z-index: -1;
}

.new-queryTableDiv {
  position: absolute;
  left: 0px;
  right: 0px;
  top: 50px;
  bottom: 50px;
}

.new-queryTableDiv-page {
  position: absolute;
  left: 0px;
  right: 0px;
  bottom: 0px;
  height: 50px;
  padding: 8px;
}
// ::v-deep .el-table__body-wrapper {
//     overflow: hidden;
//     position: relative;
//     height: 300px;
// }
:deep(.el-table__body-wrapper) {
    overflow: hidden;
    position: relative;
    height: 300px;
}
</style>